package com.ivan.toolkit.common;

import java.util.Calendar;
import java.util.Date;

import lombok.extern.log4j.Log4j2;

@Log4j2
public final class SystemTime {

	private static String osName = null;
	

	/**
	 * get operate system name
	 */
	public static String getOsName() {
		if(osName == null) {
			try {
				osName = System.getProperty("os.name");		
			} catch(SecurityException e) {
				osName = "Unknown";
			} 
		}
		return osName;
	}
	
	/**
	 * is windows
	 */
	private static final StringBuffer sbWin = new StringBuffer("Windows");
	private static boolean isWindows() {
		return getOsName().contains(sbWin.subSequence(0, sbWin.length()));
	}
	/**
	 * is linux
	 */
	private static final StringBuffer sbLnx = new StringBuffer("Linux");
	private static boolean isLinux() {
		return getOsName().contains(sbLnx.subSequence(0, sbLnx.length()));
	}
	
	/**
	 * Note: change system time, maybe make the timers wrong
	 * @param date 
	 */
	public static void set(long date) {
		if(isWindows()) {
			// windows
			try{
				
				log.info("Set system time, OS: Windows");
				
				java.text.SimpleDateFormat dateFormat = 
					new java.text.SimpleDateFormat("yyyy-MM-dd");
				
				java.text.SimpleDateFormat timeFormat = 
					new java.text.SimpleDateFormat("HH:mm:ss");
				
				String dateCmd = "cmd /c date " + dateFormat.format(date);
				java.lang.Runtime.getRuntime().exec(dateCmd);
				log.info("EXECUTE: " + dateCmd);
				
				String timeCmd = "cmd /c time " + timeFormat.format(date);
				java.lang.Runtime.getRuntime().exec(timeCmd); 
				log.info("EXECUTE: " + timeCmd);
				
			} catch(Exception ex) {
				log.error("Set system time failed.", ex);
			}
		} else if(isLinux()) {
			
			// Linux
			try{
				
				log.info("Set system time, OS: Linux");
				
				java.text.SimpleDateFormat dateFormat = 
					new java.text.SimpleDateFormat("yyyy/MM/dd");
				
				java.text.SimpleDateFormat timeFormat = 
					new java.text.SimpleDateFormat("HH:mm:ss");
				
				String dateCmd = "date -s " + dateFormat.format(date);
				java.lang.Runtime.getRuntime().exec(dateCmd);
				log.info("EXECUTE: " + dateCmd);
				
				String timeCmd = "date -s " + timeFormat.format(date);
				java.lang.Runtime.getRuntime().exec(timeCmd);
				log.info("EXECUTE: " + timeCmd);
				
			}catch(Exception ex) {
				log.error("Set system time failed.", ex);
			}
		} else {
			log.error("Set system time failed. Unsupport OS: " + osName);
		}
	}
	
	public static void set(Calendar date) {
		if(date != null) {
			set(date.getTimeInMillis());
		}
	}
	
	public static void set(Date date) {
		if(date != null) {
			set(date.getTime());
		}
	}
	
}
